<template>
  <div class="billing-rules-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>计费规则设置</span>
        </div>
      </template>

      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="160px"
      >
        <el-form-item label="计费规则" prop="deductionRules">
          <el-radio-group
            v-model="formData.deductionRules"
            @change="handleRuleChange"
          >
            <!-- <el-radio label="rule1">计费规则1</el-radio> -->
            <el-radio label="rule2">计费规则（按时长）</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 计费规则1的表单 -->
        <div v-if="formData.deductionRules === 'rule1'" class="rule-form">
          <el-form-item label="使用期限(日)" prop="lifeSpan">
            <el-input-number
              v-model="formData.lifeSpan"
              :min="0"
              :max="120"
              placeholder="请输入使用期限(日)"
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="花费金额(元)" prop="amountApent">
            <el-input-number
              v-model="formData.amountApent"
              :min="0"
              :precision="2"
              placeholder="请输入花费金额"
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="saveRule1"
              >保存规则1设置</el-button
            >
          </el-form-item>
        </div>

        <!-- 计费规则2的表单 -->
        <div v-if="formData.deductionRules === 'rule2'" class="rule-form">
          <el-form-item label="温差系数" prop="coefficient1">
            <el-input-number
              v-model="formData.coefficient1"
              :min="0"
              :precision="2"
              placeholder="请输入温差系数"
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="管理费" prop="coefficient2">
            <el-input-number
              v-model="formData.coefficient2"
              :min="0"
              :precision="2"
              placeholder="请输入管理费"
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="基础费" prop="coefficient3">
            <el-input-number
              v-model="formData.coefficient3"
              :min="0"
              :precision="2"
              placeholder="请输入基础费"
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="实际扣费" prop="coefficient3">
            <div
              style="
                text-align: center;
                display: flex;
                align-items: center;
                justify-content: center;
                line-height: 1.4;
              "
            >
              <span style="margin: 0 6px">(</span>
              <span><span style="font-weight: bold;font-size: 16px;">{{ formData.coefficient1 }}</span><br />温差</span>
              <span style="margin: 0 6px">+</span>
              <span><span style="font-weight: bold;font-size: 16px;">{{ formData.coefficient2 }}</span><br />管理费</span>
              <span style="margin: 0 6px">+</span>
              <span><span style="font-weight: bold;font-size: 16px;">{{ formData.coefficient3 }}</span><br />基础费</span>
              <span style="margin: 0 6px">)</span>
              <span style="margin: 0 6px">*</span>
              <span>1(小时)</span>
              <span style="margin: 0 6px">=</span>
              <span>{{ calculationResult }}(元/小时)</span>
            </div>
          </el-form-item>

          <!-- <el-form-item label="计算结果(元/小时)">
            <el-input
              :value="calculationResult"
              readonly
              style="width: 200px ; margin-right: 10px"
              placeholder="计算结果将在这里显示"
            />元
          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" @click="saveRule2">设置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getDeductionRules,
  updateTimeLimit,
  updateRole,
} from "@/api/equipmentManagement/billingRules";

const formRef = ref();

const formData = reactive({
  id: "",
  deductionRules: "rule2",
  lifeSpan: null,
  amountApent: null,
  coefficient1: 0,
  coefficient2: 0,
  coefficient3: 0,
  basicCoffcient: null,
});

const rules = {
  lifeSpan: [{ required: false, message: "请输入使用期限", trigger: "blur" }],
  amountApent: [
    { required: false, message: "请输入花费金额", trigger: "blur" },
  ],
  coefficient1: [{ required: false, message: "请输入系数1", trigger: "blur" }],
  coefficient2: [{ required: false, message: "请输入系数2", trigger: "blur" }],
  coefficient3: [{ required: false, message: "请输入系数3", trigger: "blur" }],
};

const calculationResult = computed(() => {
  if (formData.deductionRules === "rule2") {
    const result =
      formData.coefficient1 + formData.coefficient2 + formData.coefficient3;
    return result.toFixed(2);
  }
  return "";
});

const fetchBillingRules = async () => {
  try {
    const response = await getDeductionRules();
    console.log("获取到的计费规则响应:", response);
    const responseData = response.data || response;
    console.log("实际的计费规则数据:", responseData);

    if (responseData) {
      const data = responseData;
      console.log("当前规则数据:", data);
      console.log("数据的所有字段:", Object.keys(data));
      if (data.id) {
        formData.id = data.id;
        console.log("设置的ID:", formData.id);
      } else {
        console.warn("接口返回数据中没有ID字段");
      }

      formData.lifeSpan = data.lifeSpan;
      formData.amountApent = data.amountApent;
      formData.basicCoffcient = data.basicCoffcient;

      if (data.ruleSetArray && data.ruleSetArray.length > 0) {
        formData.deductionRules = "rule2";
        formData.coefficient1 = data.ruleSetArray[0] || 0;
        formData.coefficient2 = data.ruleSetArray[1] || 0;
        formData.coefficient3 = data.ruleSetArray[2] || 0;
      } else {
        formData.deductionRules = "rule1";
        formData.coefficient1 = 0;
        formData.coefficient2 = 0;
        formData.coefficient3 = 0;
      }

      console.log("设置后的表单数据:", formData);
    } else {
      console.warn("没有获取到计费规则数据");
    }
  } catch (error) {
    console.error("获取计费规则失败:", error);
    ElMessage.error("获取计费规则失败");
  }
};

const handleRuleChange = (value) => {
  console.log("切换到规则:", value);
};

const saveRule1 = async () => {
  try {
    if (!formData.id) {
      ElMessage.error("ID不能为空，请刷新页面重试");
      return;
    }

    const params = {
      lifeSpan: formData.lifeSpan,
      amountApent: formData.amountApent,
      id: formData.id,
    };

    console.log("保存规则1参数:", params);

    const response = await updateTimeLimit(params);
    if (response) {
      ElMessage.success("规则1设置保存成功");
      // 保存成功后不重新获取数据，保持用户当前的选择
    }
  } catch (error) {
    console.error("保存规则1失败:", error);
    ElMessage.error("保存规则1失败");
  }
};

const saveRule2 = async () => {
  try {
    if (!formData.id) {
      ElMessage.error("ID不能为空，请刷新页面重试");
      return;
    }

    const params = {
      ruleSetArray: [
        formData.coefficient1,
        formData.coefficient2,
        formData.coefficient3,
      ],
      id: formData.id,
    };

    console.log("保存规则2参数:", params);

    const response = await updateRole(params);
    if (response) {
      ElMessage.success("规则2设置保存成功");
      // 保存成功后不重新获取数据，保持用户当前的选择
    }
  } catch (error) {
    console.error("保存规则2失败:", error);
    ElMessage.error("保存规则2失败");
  }
};

onMounted(() => {
  fetchBillingRules();
});
</script>

<style lang="scss" scoped>
.billing-rules-container {
  padding: 20px;

  .box-card {
    max-width: 800px;
    margin: 0 auto;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: bold;
    }

    .rule-form {
      margin-top: 20px;
      padding: 20px;
      background-color: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #e9ecef;
    }

    .el-form-item {
      margin-bottom: 20px;
    }

    .el-radio-group {
      .el-radio {
        margin-right: 20px;
      }
    }
  }
}
</style>
